<template>
  <div class="login_container">
    <!-- 登录框 -->
    <div class="login_box">
      <!-- 头像区 -->
      <div class="avatar_box">
        <img src="../assets/images/logo.png" />
      </div>

      <!-- 登录表单区 -->
      <el-form ref="loginFormRef" :model="loginForm" label-width="0px" :rules="loginFormRules" class="login_form">
        <!-- 管理员名称 -->
        <el-form-item prop="mName">
          <el-input prefix-icon="iconfont icon-user" v-model="loginForm.mName"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input prefix-icon="iconfont icon-3702mima" v-model="loginForm.password" type="password"></el-input>
        </el-form-item>
        <!-- 按钮区 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="resetLoginForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 登录表单
      loginForm: {
        mName: '',
        password: ''
      },
      // 登录表单信息验证规则
      loginFormRules: {
        mName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '用户名长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 18, message: '密码长度在 4 到 18 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 重置登录表单信息
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields()
    },
    // 登录验证
    login() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return false // 验证规则未通过
        // 向后台发送请求
        const { data: res } = await this.$axios.post('/login.do', this.loginForm)

        if (!res.flag) return this.$message.error(res.message)
        window.sessionStorage.setItem('user', res.data) // 将当前用户存入 session

        this.$router.push('/home') // 页面跳转
        this.$message.success(res.message)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login_container {
  background-color: #2b4b6b;
  height: 100%;
}

.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  .avatar_box {
    height: 130px;
    width: 130px;
    border-radius: 50%;
    border: 1px solid #eee;
    padding: 10px;
    position: absolute;
    left: 50%;
    box-shadow: 0 0 10px #ddd;
    transform: translate(-50%, -50%);
    background-color: rgb(122, 214, 236);

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #fff;
    }
  }
}

.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.btns {
  display: flex;
  justify-content: flex-end;
}
</style>
